<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a :class="{active : sorter === 'weight_desc'}"
      @click="changeSorter('weight_desc')"
        href="javascript:;"
        >推荐</a
      >
      <a
      :class="{active : sorter === ''}"
      @click="changeSorter('')"
        href="javascript:;"
        >最新</a
      >
      <div class="logo"><img src="@/assets/logo.png" alt=""></div>
    </nav>

    <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="onLoad"
>
<article-item v-for="item in rows" :key="item.id" :item="item"></article-item>

</van-list>

  </div>
</template>

<script>
import { getArticles } from '@/api/article'
export default {

  name: 'article-page',
  data () {
    return {
      rows: [],
      current: 1,
      loading: false,
      finished: false,
      sorter: 'weight_desc'
    }
  },
  methods: {
    async onLoad () {
      // 分页加载思路
      // 1.需要用到van-list 组件  提供了loading状态 和load 事件
      // 2.当list滚动到底部 触发load事件 并将loading自动设置为true
      // 3.底部出现加载中 可以发送请求了
      // 4.请求完毕后 将loading 改为false
      // 5.每次请求将current+1
      // 6.请求到的数据不能直接覆盖 而是要追加到数组末尾
      const res = await getArticles({
        current: this.current,
        pageSize: 10,
        sorter: this.sorter
      })

      this.rows.push(...res.data.data.rows)
      this.loading = false
      // 防止过度操作导致的其他bug 滑到最底部自动显示没有更多了
      if (this.current >= res.data.data.pageTotal) {
        // 加载完毕了
        this.finished = true
      }
      this.current++
    },
    changeSorter (sorter) {
      // 修改排序方法
      this.sorter = sorter
      // 重置状态 为了获取数据时不受前面的影响
      this.rows = []
      this.current = 1
      this.finished = false
      // 重新发起请求手动加载更多
      // 手动加载更多 要将loading 改为true 避免重复加载
      this.loading = true

      // 调用方法发请求
      this.onLoad()
    }
  },
  async created () {

    // console.log(this.rows)
  }
}
</script>

<style lang="less" scoped>
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;
  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;
    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }
      &.active {
        color: #222;
        &::after {
          width: 14px;
        }
      }
    }
    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}

</style>
